// 加载模块
import axios from 'axios';
import {$} from './utils.js';

// 发送邮箱验证码
$('.pull-right').onclick = function (){
    // 获取邮箱
    let emailVal = $('#email').value;
    // 校验邮箱的正则
    let reg = /^\w{6,20}@[0-9a-zA-Z]{1,12}(\.[a-zA-Z]{2,3}){1,2}$/;
    if (!reg.test(emailVal)) {
        alert('邮箱格式错误！');
        return;
    }
    // 发送请求
    axios({
        method: 'post',
        url: 'http://localhost:9999/user/sendmail',
        data: {
            email: emailVal
        }
    })
    .then(res=>{
        alert(res.data.msg);
    })
    .catch(()=>{
        alert('网络异常，请重试！');
    });
};

$('.btn-block').onclick = function (){
    // 获取注册信息
    let username = $('#user').value;
    let password = $('#pass').value;
    let phone = $('#phone').value;
    let email = $('#email').value;
    let code = $('#code').value;
    let age = $('#age').value;
    let sex = $('#sex').value;
    // 校验数据格式
    let reg1 = /^\w{6,18}$/;
    if (!reg1.test(username)) {
        alert('账号格式错误！');
        return;
    }
    let reg2 = /^\w{6,18}$/;
    if (!reg2.test(password)) {
        alert('密码格式错误！');
        return;
    }
    let reg3 = /^1[3-9]\d{9}$/;
    if (!reg3.test(phone)) {
        alert('手机格式错误！');
        return;
    }
    let reg4 = /^\w{6,20}@[0-9a-zA-Z]{1,12}(\.[a-zA-Z]{2,3}){1,2}$/;
    if (!reg4.test(email)) {
        alert('邮箱格式错误！');
        return;
    }
    let reg5 = /^\d{1,3}$/;
    if (!reg5.test(age)) {
        alert('年龄输入错误！');
        return;
    }
    let reg6 = /^[男女妖]$/;
    if (!reg6.test(sex)) {
        alert('请选择性别！');
        return;
    }
    let reg7 = /\d+/;
    if (!reg7.test(code)) {
        alert('验证码格式错误！');
        return;
    }

    // 发送注册请求
    axios({
        method: 'post',
        url: 'http://localhost:9999/user/register',
        data: {
            username,
            password,
            phone,
            email,
            age,
            sex,
            code
        }
    })
    .then(res=>{
        alert(res.data.msg);
        if (res.data.code === 1) {
            // 注册成功，跳转到首页
            location.href = './index.html';
        }
    }).catch(()=>{
        alert('网络异常，请重试！');
    });
};